package com.delicious.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BaseDao {
	protected Connection conn;
	protected PreparedStatement stmt ;
	protected ResultSet rs;
	
	//打开链接
	public void openConnection(){
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/delicious","root","123456");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	//关闭链接
	public void closeConnection(){
		if(rs != null){
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		if(stmt != null){
			try {
				stmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		if(conn != null){
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	//查询
	public ResultSet executeQuery(String sql,Object[] paramters) throws SQLException{
		stmt = conn.prepareStatement(sql);
		if(paramters != null){
			for (int i = 0; i < paramters.length; i++) {
				stmt.setObject(i+1, paramters[i]);
			}
		}
		return stmt.executeQuery();
	}
	
	//增删改
	public int executeUpdate(String sql ,Object[] paramters) throws SQLException{
		stmt = conn.prepareStatement(sql);
		if(paramters != null){
			for (int i = 0; i < paramters.length; i++) {
				stmt.setObject(i+1, paramters[i]);
			}
		}
		return stmt.executeUpdate();
	}
}
